package com.zys.asseter.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zys.asseter.constant.AssetUpdateCountConstant;
import com.zys.asseter.domain.dto.AssetFingerprintInfoDTO;
import com.zys.asseter.domain.dto.AssetUpdateCountDto;
import com.zys.asseter.domain.pojo.AssetFingerprintInfoEntity;
import com.zys.asseter.domain.pojo.PageBean;
import com.zys.asseter.domain.vo.TypeTreeVO;
import com.zys.asseter.mapper.AssetFingerprintInfoMapper;
import com.zys.asseter.service.AssetFingerprintInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class AssetFingerprintInfoService {

    private final AssetFingerprintInfoMapper assetFingerprintInfoMapper;




    /**
     * 从资产信息表中插入数据到资产指纹信息表中
     */

    public void insertDataFromAssetInfoToFingerInfo() {
        assetFingerprintInfoMapper.truncateTable();
        assetFingerprintInfoMapper.insertDataFromAssetInfoToFingerInfo();
    }


    /**
     * 查询指纹信息
     * @param assetType
     * @param assetSubType
     * @return
     */

    public List<String> selectFingerName(String assetType, String assetSubType) {
        List<String> fingerList = assetFingerprintInfoMapper.selectFingerName(assetType, assetSubType);
        return fingerList;
    }


    /**
     * 根据厂商查询指纹名称
     * @param manufacturer
     * @return
     */

    public List<String> selectByManufacturer(String manufacturer) {
      List<String> strings = assetFingerprintInfoMapper.selectByManufacturer(manufacturer);
        return strings;
    }

    /**
     * 查询所有厂商
     * @return
     */

    public List<String> selectManufacturer() {
        List<String> strings = assetFingerprintInfoMapper.selectManufacturer();
        return strings;
    }

    /**
     * 新增指纹信息
     * @param dto
     */

    public void insertFingerInfo(AssetFingerprintInfoDTO dto) {
        AssetFingerprintInfoEntity e = new AssetFingerprintInfoEntity();
        BeanUtils.copyProperties(dto, e);
        e.setDelFlag("0");
        e.setCreateTime(new Date());
        e.setUpdateTime(new Date());
        e.setFingerName(dto.getManufacturer() + "-" + dto.getModel() + "-" + dto.getBrand());
        e.setId(UUID.randomUUID().toString().replace("-", ""));
        String manufacture = assetFingerprintInfoMapper.selectMCode(dto.getManufacturer());
        String model =  assetFingerprintInfoMapper.selectMoCode(dto.getModel());
        String brand =  assetFingerprintInfoMapper.selectBrCode(dto.getBrand());
        e.setManufacturerCode(manufacture);
        e.setModelCode(model);
        e.setBrandCode(brand);
        e.setFingerNameCode(manufacture + model + brand);
        String assetTypeId = assetFingerprintInfoMapper.selectId(e.getAssetType());
        e.setAssetTypeId(assetTypeId);
        assetFingerprintInfoMapper.insertFingerInfo(e);
//        String assetSubTypeCode = assetFingerprintInfoMapper.selectSubCode(e.getAssetSubType());
//        e.setAssetSubTypeCode(assetSubTypeCode);
    }

    /**
     * 根据名称删除指纹信息
     * @param id
     */
    public void deleteById(String id) {
         assetFingerprintInfoMapper.deleteById(id);
    }




    /**
     * 根据名称查询指纹信息
     *
     * @param name
     * @return
     */

    public AssetFingerprintInfoEntity getByName(String name) {
       AssetFingerprintInfoEntity info = assetFingerprintInfoMapper.getByName(name);
        return info;
    }



    /**
     *构建父子类型树形结构类
     * @return
     */
    public List<TypeTreeVO> getTypeTree() {
        // 获取所有的父类型及其对应的子类型
        List<AssetFingerprintInfoEntity> allTypes = assetFingerprintInfoMapper.selectAllTypes();


        // 构建父类型到子类型的映射
        Map<String, List<String>> parentToChildren = allTypes.stream()
                .collect(Collectors.groupingBy(
                        AssetFingerprintInfoEntity::getAssetType,
                        Collectors.mapping(AssetFingerprintInfoEntity::getAssetSubType, Collectors.toList())
                ));

        // 构建树结构
        List<TypeTreeVO> collect = parentToChildren.entrySet().stream()
                .map(entry -> {
                    TypeTreeVO typeTreeVo = new TypeTreeVO();
                    typeTreeVo.setAssetType(entry.getKey());
                    String assetTypeId = assetFingerprintInfoMapper.selectAssetTypeID(entry.getKey());
                    long count = assetFingerprintInfoMapper.countAssetsByModelId(assetTypeId);
                    typeTreeVo.setNum(count);
                    typeTreeVo.setAssetTypeId(assetTypeId);
                    typeTreeVo.setAssetSubType(entry.getValue().stream()
                            .map(subType -> {
                                TypeTreeVO childTypeTreeVo = new TypeTreeVO();
                                childTypeTreeVo.setAssetType(subType);
                                String code = assetFingerprintInfoMapper.selectSubTypeCode(subType);
                                Long result = assetFingerprintInfoMapper.countBySubTypeCode(assetTypeId,code);
                                childTypeTreeVo.setAssetSubTypeId(code);
                                childTypeTreeVo.setNum(result);
                                return childTypeTreeVo;
                            })
                            .collect(Collectors.toList()));
                    return typeTreeVo;
                })
                .collect(Collectors.toList());
        return collect;
    }
    



    /**
     * 根据可选条件分页查询
     * * @param pageNum
     *
     * @param pageSize
     * @param fingerName
     * @param manufacturer
     * @return
     */
    public PageBean<AssetFingerprintInfoEntity> ConditionPageQuery(Integer pageNum, Integer pageSize, String fingerName, String manufacturer) {
        PageBean<AssetFingerprintInfoEntity> pageBean = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<AssetFingerprintInfoEntity> assetFingerprintInfoEntities =
                assetFingerprintInfoMapper.ConditionPageQuery(fingerName, manufacturer);

        Page<AssetFingerprintInfoEntity> page = (Page<AssetFingerprintInfoEntity>) assetFingerprintInfoEntities;
        pageBean.setTotal(page.getTotal());
        pageBean.setItems(page.getResult());

        return pageBean;
    }

    /**
     * 资产表新增一条数据的时候判断对应的指纹在指纹表中是否存在
     */
    public Integer judgeFingerInfo(String code) {
         Integer result = assetFingerprintInfoMapper.judgeFingerInfo(code);
         return  result;
    }

    public Integer countDomainUsage(String domainName) {
        return assetFingerprintInfoMapper.countDomainUsage(domainName);
    }

    public void updateCount(String name, AssetUpdateCountConstant type) {
        Integer i = assetFingerprintInfoMapper.CountByType(name,type.getType());
        String count = String.valueOf(i);
        switch (type){
            case DOMAIN_ADDRESS:
                assetFingerprintInfoMapper.updateDomainTimes(name,count);
                break;
            case ICP_RECORD_NAME:
                assetFingerprintInfoMapper.updateIcpTimes(name,count);
                break;
        }
    }


    @Transactional
    public void initCount() {
        List<AssetUpdateCountDto> totalData = assetFingerprintInfoMapper.selectDomainIcp();
        for (AssetUpdateCountDto dto : totalData) {
            if (StringUtils.isNotBlank(dto.getIcpRecordNumber())) {
                updateCount(dto.getIcpRecordNumber(), AssetUpdateCountConstant.ICP_RECORD_NAME);
            }
            if(StringUtils.isNotBlank(dto.getDomainAddress())){
                updateCount(dto.getDomainAddress(),AssetUpdateCountConstant.DOMAIN_ADDRESS);
            }
        }
    }
}
